<template>
  <div>
    <el-container class="datamining-container">
      <el-header ref="header" style="margin-top: 10px;height: auto;">
        <el-row>
          <el-select
            v-model="search_query.crmdatamining_id"
            placeholder="选择数据集"
            style="width: 200px"
            clearable
            @change="handleChangeData"
          >
            <el-option
              label="所有"
              value=""
            />
            <el-option v-for="item in dataMinings" :key="item.id" :label="item.subject" :value="item.id" />
          </el-select>
          <el-button
            style="width: 40px"
            title="管理"
            icon="el-icon-setting"
            @click="innerDialogVisible = true"
          />

          <el-select
            v-model="search_query.favorite"
            placeholder="收藏"
            style="width: 100px"
            clearable
            @change="handleSearch"
          >
            <el-option
              label="所有"
              value=""
            />
            <el-option
              label="收藏"
              value="true"
            />
            <el-option
              label="未收藏"
              value="false"
            />
          </el-select>
          <el-select
            v-model="search_query.processed"
            placeholder="选择处理类型"
            style="width: 100px"
            clearable
            @change="handleSearch"
          >
            <el-option
              label="所有"
              value=""
            />
            <el-option
              label="已处理"
              value="true"
            />
            <el-option
              label="未处理"
              value="false"
            />
          </el-select>
          <el-select
            v-model="search_query.operator_id"
            v-loading="ownersLoading"
            placeholder="选择业务"
            filterable
            style="width: 100px"
            clearable
          >
            <el-option value="" label="所有业务员" />
            <el-option
              v-for="user in users"
              :key="user.id"
              :label="user.show_name"
              :value="user.id"
            />
          </el-select>
          <el-switch
            v-model="allvalidstar"
            title="所有有效分数数据"
            active-text="所有有效数据"
            inactive-text="按分数"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
          <el-input-number v-if="!allvalidstar" v-model="search_query.star" :min="-2" :max="10" label="star" style="width: 100px" @change="handleSearch" />
          <el-input
            v-model="search_query.kw"
            style="width: 350px"
            placeholder="输入 任意字符 进行筛选"
            class="input-with-select"
            clearable
            @keyup.native.enter="handleSearch"
          >
            <el-button slot="append" icon="el-icon-search" :loading="listLoading" @click="handleSearch">搜索</el-button>
          </el-input>
          <div v-if="search_query.crmdatamining_id !== ''" style="float: right">
            <crmdownloador
              :table-name="downloadTemp.table_name"
              :fields="downloadTemp.fields"
              :filters="downloadTemp.filters"
              :available-fields="availableFields"
            />
          </div>
        </el-row>
        <el-row style="margin-top: 10px">
          <el-button v-for="(item, index) in dataset.stats" :key="index" size="mini" :type="item.unprocessed_count ? 'primary': 'success'" :title="'未处理:' + item.unprocessed_count" @click="hanSearchStar(item.star)">{{ item.star }}</el-button>
          <span v-if="dataset.total_unprocessed || dataset.total_processed" style="display: inline-block;">未处理:{{ dataset.total_unprocessed }}|已经处理:{{ dataset.total_processed }}</span>
        </el-row>
        <el-alert type="info">任意行双击，标识处理</el-alert>
      </el-header>
      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          class="custom-table"
          :row-class-name="tableRowClassName"
          @row-dblclick="handleRowDblclick"
          @sort-change="handleSort"
        >
          <el-table-column align="center" label="线索参数" width="200" prop="field1" sortable="custom">
            <template slot-scope="scope">
              <div v-for="(value, key) in field_name_map" v-if="scope.row[key] !== ''" :key="key" style="display: block">
                <span>{{ value }}:</span><span><a target="_blank" style="color: blue;" :href="'https://www.google.com/search?q=' + scope.row[key]">{{ scope.row[key] }}</a></span>
              </div>
              <span>创建时间:{{ scope.row.create_at }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="摘要" prop="summary" sortable="custom">
            <template slot-scope="scope">
              <div style="display: block" v-html="scope.row.summary" />
              <div class="image-gallery-container">
                <div class="image-gallery">
                  <el-image
                    v-for="(image, index) in scope.row.thumbnail"
                    :key="index"
                    :preview-src-list="scope.row.thumbnail"
                    :src="image"
                    class="gallery-image"
                  />
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="处理" width="250" prop="has_email" sortable="custom">

            <template slot-scope="scope">
              <!--               <el-carousel height="150px" v-if="scope.row.thumbnail && scope.row.thumbnail.length > 0">-->
              <!--                <el-carousel-item v-for="(image, index) in scope.row.thumbnail" :key="index">-->
              <!--                  <img :src="image" style="width: 100%; height: 100%; object-fit: cover;" />-->
              <!--                </el-carousel-item>-->
              <!--              </el-carousel>-->
              <h3>评分: {{ scope.row.star }}分</h3>
              <el-row v-if="!scope.row.favorite" style="margin-bottom: 20px;">
                <el-button v-if="!scope.row.processed" type="danger" icon="el-icon-delete" @click="handleSet({id: scope.row.id, processed: true},'processed')">垃圾数据</el-button>
                <el-button v-else type="info" icon="el-icon-error" @click="handleSet({id: scope.row.id, processed: false},'processed')">取消处理标记</el-button>
              </el-row>
              <el-row v-else style="margin-bottom: 20px;">
                <el-button v-if="!scope.row.processed" type="primary" icon="el-icon-success" @click="handleSet({id: scope.row.id, processed: true},'processed')">标记已处理</el-button>
                <el-button v-else type="info" icon="el-icon-error" @click="handleSet({id: scope.row.id, processed: false},'processed')">取消处理标记</el-button>
              </el-row>
              <el-row>
                <el-button v-if="!scope.row.favorite" type="success" icon="el-icon-star-on" @click="handleSet({id: scope.row.id, favorite: true},'favorite')">收藏数据</el-button>
                <el-button v-else type="info" icon="el-icon-star-off" @click="handleSet({id: scope.row.id, favorite: false},'favorite')">取消收藏</el-button>
              </el-row>
              <el-row style="margin-top: 20px; margin-bottom: 20px">
                <el-select
                  v-model="scope.row.operator_id"
                  placeholder="指定业务"
                  filterable
                  clearable
                  @change="handleChangeOperator(scope.row)"
                >
                  <el-option
                    v-for="user in users"
                    :key="user.id"
                    :label="user.show_name"
                    :value="user.id"
                  />
                </el-select>
              </el-row>
              <div style="height: auto;overflow-y: auto;">
                <el-timeline style="padding-left: 1px;">
                  <el-timeline-item v-for="(op, index) in scope.row.opHistories" :key="index" :timestamp="op.create_at" placement="top">
                    <el-card shadow="hover">
                      {{ op.note }}
                    </el-card>
                  </el-timeline-item>
                </el-timeline>
              </div>
              <el-button type="primary" size="mini" @click="handleAddOpHistory(scope.row)">添加记录</el-button>
            </template>
          </el-table-column>
          <!--           <el-table-column align="center" label="操作" width="200" fixed="right">-->
          <!--              <template slot-scope="scope">-->
          <!--                <el-button v-show="!scope.row.edit" size="mini" icon="el-icon-edit" type="warning"-->
          <!--                           @click="handleAction('edit', scope.row)" plain>修改-->
          <!--                </el-button>-->
          <!--                <el-button v-show="!scope.row.edit" size="mini" icon="el-icon-delete" type="danger"-->
          <!--                           @click="handleAction('delete', scope.row)" plain>删除-->
          <!--                </el-button>-->
          <!--              </template>-->
          <!--            </el-table-column>-->
        </el-table>

      </el-main>
      <el-footer ref="footer" height="auto" class="pagination-footer">
        <el-pagination
          v-if="data.length"
          ref="pagination"
          background
          class="mt-pagination"
          :current-page="search_query.page"
          :page-sizes="[10,20,50,100]"
          :page-size="search_query.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="search_query.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-footer>
    </el-container>
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="editVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item label="数据集名称" prop="name">
          <el-input v-model="temp.subject" />
        </el-form-item>
        <el-form-item label="框架树父ID" prop="description">
          <el-input v-model="temp.parent_topic_id" />
        </el-form-item>
        <el-form-item label="背调prompts" prop="description">
          <el-input v-model="temp.background_check_aiprompt_id" />
        </el-form-item>
        <el-form-item label="判定AIPrompt" prop="description">
          <el-input v-model="temp.aiprompt_id" />
        </el-form-item>
        <el-form-item label="字段名称" prop="description">
          <el-input v-model="temp.field_name_map" />
        </el-form-item>
        <el-form-item label="业务员tag" prop="description">
          <el-input v-model="temp.staff_tag" />
        </el-form-item>
        <el-form-item label="全部完成" prop="description">
          <el-switch
            v-model="temp.is_finished"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="只处理收藏" prop="description">
          <el-switch
            v-model="temp.distribute_favorite_only"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
        <el-form-item label="日分配" prop="description">
          <el-input-number v-model="temp.max_info_daily" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      append-to-body
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-button
        type="primary"
        class="el-icon-plus add-btn"
        :disabled="listLoading"
        @click="handleAction('create', '添加')"
      >添加
      </el-button>
      <el-table
        v-loading="listLoading"
        :data="dataMinings"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column align="center" width="100" prop="id" label="id" sortable="custom" />
        <el-table-column prop="subject" label="名称" />
        <el-table-column prop="parent_topic_id" label="数据源树ID" />
        <el-table-column prop="aiprompt_id" label="AIPrompt" />
        <el-table-column prop="staff_tag" label="业务员tag" />
        <el-table-column prop="is_finished" label="处理完成">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.is_finished"
              disabled
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </template>
        </el-table-column>
        <el-table-column prop="max_info_daily" label="日分配" />
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleAction('edit', scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/crmm'
import { Get as GetEntry, Put as PutEntry } from '@/api/crm/crmdatamingentry'
import { GetStatics } from '@/api/crm/crmdatamingentry'
import { CRMGetProjectUsers as GetUsers } from '@/api/crm/crmmanage'
import qs from 'qs'
import Crmdownloador from '../../components/crmdownloador'
import Imagezome from './imagezome'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  name: 'Datamining',
  components: { Imagezome, Crmdownloador },
  data() {
    return {
      downloadTemp: {
        table_name: 'CRMDataMiningEntry', // 假设表名是 CRMProduct
        fields: ['field1', 'field2', 'field3', 'field4', 'field5', 'field6', 'field7', 'field8', 'summary', 'phone', 'email', 'website'],
        filters: {
          crmdatamining_id: '',
          favorite: true,
          processed: true
        },
        kw: '',
        total: 0,
        order_by: '',
        order_desc: 0
      },
      availableFields: [
        { label: '参数1', value: 'field1' },
        { label: '参数2', value: 'field2' },
        { label: '参数3', value: 'field3' },
        { label: '参数4', value: 'field4' },
        { label: '参数5', value: 'field5' },
        { label: '参数6', value: 'field6' },
        { label: '参数7', value: 'field7' },
        { label: '参数8', value: 'field8' },
        { label: 'website', value: 'website' },
        { label: '电话', value: 'phone' },
        { label: '邮箱', value: 'email' },
        { label: '摘要', value: 'summary' }
      ],
      showDownload: false,
      generateing: false,
      download_url: '',
      datasets: [],
      dataset: {
        stats: [],
        total_processed: 0,
        total_unprocessed: 0
      },
      ownersLoading: false,
      users: [],
      editVisible: false,
      dataMinings: [],
      field_name_map: {
        'field1': '参数1',
        'field2': '参数2',
        'field3': '参数3',
        'field4': '参数4',
        'field5': '参数5',
        'field6': '参数6',
        'field7': '参数7',
        'field8': '参数8'
      },
      table_name: 'CRMDataMining',
      data: [],
      listLoading: false,
      kwInput: '',
      activeNames: [],
      allvalidstar: true,
      search_query: {
        star: 0,
        kw: '',
        operator_id: '',
        crmdatamining_id: '',
        favorite: '',
        processed: 'false',
        order_by: '',
        order_desc: '',
        // pagination
        pagesize: 10,
        page: 1,
        total: 0
      },
      favorite: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      predefineColors: [
        '#6C6762',
        '#67C23A',
        '#F56C6C',
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#00ced1',
        '#1e90ff',
        '#c71585'
      ],
      temp: {
        subject: '',
        is_finished: false,
        field_name_map: '',
        parent_topic_id: '',
        background_check_aiprompt_id: '',
        distribute_favorite_only: false,
        aiprompt_id: '',
        staff_tag: '',
        max_info_daily: 30
      },
      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    this.handleFetchGetUsers()
    this.handleGetDataMings()
  },
  methods: {
    handleRowDblclick(row, column, event) {
    // 防止与其他点击事件冲突
      event.preventDefault()

      // 如果已经处理过，则不执行任何操作
      if (row.processed) {
        return
      }

      this.$set(row, 'processing', true)

      // 执行标记处理的操作
      this.handleSet({ id: row.id, processed: true }, 'processed')
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'even-row'
      } else {
        return 'odd-row'
      }
    },
    extractBusinessSummary(content) {
      const businessRegex = /\*\*主营业务:\*\*\s*(.*?)(?=\n|$)/
      const match = content.match(businessRegex)

      if (match && match[1]) {
        return match[1].trim()
      } else {
        const summary = content.trim().slice(0, 20)
        return summary + (summary.length >= 20 ? '...' : '')
      }
    },
    handleGetStaticstatics() {
      GetStatics({ crmdatamining_id: this.search_query.crmdatamining_id }).then(response => {
        this.datasets = response.data
        if (this.datasets.length) {
          this.dataset = this.datasets[0]
        }
      }).catch(error => {
        console.error('Failed to fetch data', error)
      })
    },
    handleAddOpHistory(row) {
      this.$prompt('请输入操作记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '操作记录不能为空'
      }).then(({ value }) => {
        Post({ 'note': value, 'table_name': 'CRMDataMiningOphistory', 'crmdataminingentry_id': row.id }).then((response) => {
          this.notify('添加成功')
        })
      }).catch(() => {
      })
    },
    handleChangeOperator(row) {
      PutEntry(row.id, { 'operator_id': row.operator_id }).then((response) => {
        this.notify('更新成功')
      })
    },
    handleFetchGetUsers() {
      this.ownersLoading = true
      GetUsers(null, qs.stringify({ 'is_active': 1 }))
        .then(response => {
          this.ownersLoading = false
          this.users = response.data.data
        })
        .catch(e => {
          this.ownersLoading = false
        })
    },
    handleGetOpHistory(crmdataminingentry_id) {
      Get(null, qs.stringify({ table_name: 'CRMDataMiningOphistory', crmdataminingentry_id: crmdataminingentry_id })).then(response => {
        this.opHistories = response.data.data
      })
    },
    handleGetDataMings() {
      Get(null, qs.stringify({ table_name: 'CRMDataMining' })).then(response => {
        this.dataMinings = response.data.data
      })
    },
    resetTemp() {
      this.temp = {
        subject: '',
        is_finished: false,
        field_name_map: '',
        parent_topic_id: '',
        background_check_aiprompt_id: '',
        distribute_favorite_only: false,
        aiprompt_id: '',
        staff_tag: '',
        max_info_daily: 15
      }
    },
    getList() {
      this.listLoading = true
      const query = Object.assign({}, this.search_query)
      if (this.search_query.favorite === 'true' || this.search_query.star === -2 || this.allvalidstar) {
        // 删掉这个属性
        delete query.star
      }
      if (this.allvalidstar) {
        query.star__gte = 0
      }
      GetEntry(null, qs.stringify(query))
        .then(response => {
          this.data = response.data.data
          this.listLoading = false
          this.search_query.total = response.data.total
          this.downloadTemp.total = response.data.total
          this.handleGetStaticstatics()
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.width = '640px'
          this.title = '添加'
          this.resetTemp()
          this.editVisible = true
          break
        case 'delete':
          this.width = '640px'
          this.title = `确认要删除:${row.subject}?`
          this.temp = Object.assign({}, row)
          this.editVisible = true
          break
        case 'edit':
          this.width = '640px'
          this.title = `修改:${row.subject}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.editVisible = true
          break
      }
    },
    handleSet(row, field) {
      PutEntry(row.id, { [field]: row[field] }).then((response) => {
        this.innerDialogVisible = false
        this.getList()
        this.notify('更新成功')
      })
    },
    confirm() {
      const _data = this.temp
      _data.table_name = 'CRMDataMining'
      switch (this.action) {
        case 'create':
          Post(_data
          ).then(response => {
            this.editVisible = false
            this.handleGetDataMings()
            this.notify('添加成功')
          })
          break
        case
          'delete'
          :
          Delete(_data.id, this.temp).then((response) => {
            this.editVisible = false
            this.handleGetDataMings()
            this.$emit('reload')
            this.notify('删除成功')
          })
          break
        case
          'edit'
          :
          Put(_data.id, _data).then((response) => {
            this.editVisible = false
            this.handleGetDataMings()
            this.notify('更新成功')
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.search_query.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.search_query.page = val
      this.getList()
    },
    hanSearchStar(star) {
      this.allvalidstar = false
      this.search_query.star = star
      this.getList()
    },
    handleChangeData() {
      this.dataMinings.forEach(item => {
        if (item.id === this.search_query.crmdatamining_id) {
          const field_names = item.field_name_map.split('|')
          for (let i = 0; i < field_names.length; i++) {
            this.field_name_map['field' + (i + 1)] = field_names[i]
          }
        }
      })
      this.handleSearch()
    },
    // 点击搜索
    handleSearch() {
      this.search_query.page = 1
      this.downloadTemp.filters.crmdatamining_id = this.search_query.crmdatamining_id
      this.getList()
    },
    handleSort(v) {
      this.search_query.order_by = v.prop
      this.search_query.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    }
  }
}
</script>

<style scoped>

.custom-table >>> .el-table__row.processing {
  background-color: #ad6868 !important;
}

.custom-table >>> .even-row {
  background-color: #f5f7fa;
}

.custom-table >>> .odd-row {
  background-color: #ffffff;
}

.custom-table >>> .el-table__body tr:hover > td {
  background-color: #e6f7ff !important;
}

/* 可选：修改表头样式 */
.custom-table >>> .el-table__header-wrapper th {
  background-color: #ebeef5;
  color: #606266;
  font-weight: bold;
}

/* 可选：修改表格边框颜色 */
.custom-table >>> .el-table--border, .custom-table >>> .el-table--group {
  border-color: #dcdfe6;
}

.custom-table >>> .el-table td, .custom-table >>> .el-table th.is-leaf {
  border-color: #dcdfe6;
}
.image-gallery-container {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 10px; /* 为滚动条留出空间 */
}

.image-gallery {
  display: inline-flex; /* 改为 inline-flex */
  flex-wrap: nowrap;
  gap: 5px; /* 图片之间的间隔 */
  justify-content: center; /* 居中对齐 */
  min-width: 100%; /* 确保内容少时也能居中 */
}

.gallery-image {
  flex: 0 0 auto;
  width: 100px;
  height: 100px;
  object-fit: cover;
}

/* 自定义滚动条样式（可选） */
.image-gallery-container::-webkit-scrollbar {
  height: 8px;
}

.image-gallery-container::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.image-gallery-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.image-gallery-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}
.pagination-footer {
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-top: 1px solid #e6ebf5;
}

.datamining-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.el-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  overflow-y: auto; /* Add this to allow scrolling in main content */
}

.el-table {
  flex: 1;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
  /*margin: 168px auto !important;*/
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
